$(function () {


    $("#jqGrid").jqGrid({
        url: baseURL + 'generator/basetemplate/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden:true },
			{ label: '流程模板名称', name: 'templateName', index: 'template_name', width: 80 }, 			
			{ label: '创建人id', name: 'templateCreator', index: 'template_creator', width: 80,hidden:true  },
			{ label: '创建人姓名', name: 'templateCreatorName', index: 'template_creator_name', width: 80 }, 			
			{ label: '创建时间', name: 'creationTime', index: 'creation_time', width: 80 }, 			
			// { label: '修改时间', name: 'updateTime', index: 'update_time', width: 80 },
            { label:'操作',width: 80,formatter:function(cellvalue, options, row){
            	/*console.log(cellvalue);
            	console.log(options);
            	console.log(row.id);*/
            	return '<a class="btn-set" href="javascript:void(0);" data-id="' + row.id + '">编辑模板</a>';}
            }
        ],

		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            $('#jqGrid').on('click', '.btn-set', function (e) {
                var templateId = $(this).attr('data-id');
                // console.log(templateId);
                var pWindow = window.parent;
                var oIframe = $('#main-content iframe', pWindow.document);

                // 改变首页的 indexVm 的 data，触发 updated
                pWindow.indexVm.main = 'modules/base/templates.html?templateId=' + templateId;

                pWindow.location.hash = 'modules/base/templates.html?templateId=' + templateId;
                oIframe.attr('src','modules/base/templates.html?templateId=' + templateId);
            })

        }
    });

    $('#template-form').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {/*输入框不同状态，显示图片的样式*/
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {/*验证*/
            templateName: {/*键名username和input name值对应*/
                message: '模板名校验失败',
                validators: {
                    notEmpty: {/*非空提示*/
                        message: '模板名不能为空'
                    },
                    stringLength: {
                        max: 60,
                        message: '输入超出长度'
                    }
                }
            }
        }
    });

});


var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		msgs: null,
		user: {},
		title: null,
		baseTemplate: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.baseTemplate = {};
		},
		getUser: function () {
			console.log('获取用户');
            $.getJSON(baseURL + "sys/user/info", function(r){
                // vm.msgs = r.msg;
                vm.user = r.user;
                // console.log(vm.msgs);
                console.log(vm.user);
            });
        },
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return false;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
            // $('#template-form').bootstrapValidator('validate');
            // console.log($('#template-form').bootstrapValidator('validate'));
            var bootstrapValidator = $("#template-form").data('bootstrapValidator');
            bootstrapValidator.validate();
            console.log(bootstrapValidator.isValid());
            if(!bootstrapValidator.isValid()) {
            	console.log('验证不通过');
                alert('请输入合法值');
            	return false;
			} else {
            	console.log('验证通过');
                var url = vm.baseTemplate.id == null ? "generator/basetemplate/save" : "generator/basetemplate/update";
                vm.baseTemplate.templateCreatorName = vm.user.username;
                vm.baseTemplate.templateCreator = vm.user.userId;
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.baseTemplate),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
			}
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "generator/basetemplate/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "generator/basetemplate/info/"+id, function(r){
                vm.baseTemplate = r.baseTemplate;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		}
	},
    created: function(){
        this.getUser();
    }
});